package com.bdqn.petmalldemo.aspect;

import com.alibaba.fastjson.JSONObject;
import com.bdqn.petmalldemo.common.KetaiException;
import com.bdqn.petmalldemo.common.ResultCodeEnum;
import com.bdqn.petmalldemo.common.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


/**
 * @Author:彭俊
 * @description:日志切面
 * @date:2020/3/11250
 */
@Component
@Aspect
@Slf4j
public class AOPLogAspect {
    /**
     * 指定需要切入的位置
     */
    @Pointcut(value = "execution(public * com.bdqn.petmalldemo.controller.*.*(..))")
    public void controllerMethodPointCut() {

    }

    @Around(value = "controllerMethodPointCut()")
    public Object aroundLog(ProceedingJoinPoint joinPoint) {
        //获取控制器名称
        String controllerName = joinPoint.getSignature().getDeclaringTypeName();
        //处理器名称,也就是请求路径
        String handlerName = joinPoint.getSignature().getName();
        //获取请求参数
        Object[] methodParames = joinPoint.getArgs();
        log.info("请求路径:{},{}", controllerName, handlerName);
        for (int i=0;i<methodParames.length;i++){
            Object methodParame=methodParames[i];
            if (methodParame!=null) {
                log.info("参数类型:{}",methodParame.getClass().getName());
                log.info("参数:{}",methodParame.toString());
            }

        }
        Object result =null;
        //执行方法
        try {
             result = joinPoint.proceed();
        } catch (Throwable throwable) {
            log.warn(throwable.getMessage(),throwable);
            //判断异常类型
            if (throwable instanceof KetaiException) {
                KetaiException ketaiException=(KetaiException)throwable;
                result= ReturnResult.error().code(ketaiException.getCode())
                        .msg(ketaiException.getMessage());
            }
            if (throwable instanceof Exception){
                //处理TokenCache中的数据已经失效,根据请求路径来判断是否为登录校验的接口
                if (handlerName.contains("checkActive")) {
                    result=ReturnResult.error().code(ResultCodeEnum.TOKEN_INVALID.getCode()).msg(ResultCodeEnum.TOKEN_INVALID.getMsg());
                }
                result=ReturnResult.error().msg(throwable.getMessage());
            }
        }finally {
            //打印返回参数
            log.info("响应数据:{}", result==null ? "无": JSONObject.toJSONString(result));
            return result;
        }
    }
}




